// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database({
  throwOnNotFound: false
})
const _ = db.command
const $ = db.command.aggregate

// 检查支付是否超时
async function checkClosePayment() {
  const prev = new Date().getTime() - 15 * 60 * 1000;
  await db.collection('tb_order')
    .where({
      order_state: 0,
      created_time: _.lt(prev),
    })
    .update({
      data: {
        order_state: 1,
        modified_user_id: '<system>',
      }
    })
}

// 检查预约卡券是否失效
async function checkCouponValid() {
  const now = new Date().getTime();
  await db.collection('tb_coupon')
    .where({
      coupon_state: 0,
      end_time: _.lt(now)
    })
    .update({
      data: {
        coupon_state: 3
      }
    })
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  await checkClosePayment();
  await checkCouponValid();

  return {
    event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,
  }
}